package com.lc.demo.controller;

import com.lc.demo.bean.Cart;
import com.lc.demo.bean.Goods;
import com.lc.demo.bean.User;
import com.lc.demo.result.ResponseMessage;
import com.lc.demo.service.CartService;
import com.lc.demo.service.GoodsService;
import com.lc.demo.service.UserService;
import com.lc.demo.util.BeanUtil;
import com.lc.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: sakila
 * @Date: 2022/03/07/19:31
 * @Description:
 */
@RestController
@CrossOrigin
@RequestMapping("/api/carts")
public class CartController {

    @Autowired
    private CartService cartService;


    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @GetMapping()
    public ResponseMessage getCartList(HttpServletRequest request) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        String authorization = request.getHeader("Authorization");
        // 5. 请求头中获取令牌
        Claims claims = JwtUtil.parseJWT(authorization);
        String subject = claims.getSubject();
        User userFind = new User();
        userFind.setEmail(subject);
        User one = userService.findOne(userFind);

        List<Cart> cartList = cartService.getCartList(one.getId());

        ArrayList<Map<String, Object>> returnList = new ArrayList<>();

        //根据cart 查询出 商品Id
        for (Cart cart : cartList) {
            Goods goods = goodsService.selectGoodsByGoodsId(cart.getGoodsId());
            Map<String, Object> stringObjectMap = BeanUtil.transBean2Map(goods);

            stringObjectMap.put("goodsNum", cart.getGoodsNum());
            returnList.add(stringObjectMap);
        }
        return ResponseMessage.successWithData(returnList);
    }


    @PostMapping()
    public ResponseMessage changeCart(@RequestBody Cart cart, HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        // 5. 请求头中获取令牌
        Claims claims = JwtUtil.parseJWT(authorization);
        String subject = claims.getSubject();
        User userFind = new User();
        userFind.setEmail(subject);
        User one = userService.findOne(userFind);

        cartService.changeCart(cart, one.getId());
        return ResponseMessage.success();
    }


    //
}
